﻿using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using PaymentServiceFactory.Data;
using PaymentServiceFactory.Services.Interfaces;

namespace PaymentServiceFactory.Services.Implementations
{
    //public class PayPalPayment : IPaymentService
    //{
    //    private readonly IHttpClientFactory _httpClientFactory;
    //    private readonly ILogger<PayPalPayment> _logger;
    //    private readonly IOrderDetrInfoRepository _orderRepository;

    //    // 移除了 orderId 构造函数参数
    //    public PayPalPayment(
    //        IHttpClientFactory httpClientFactory,
    //        ILogger<PayPalPayment> logger,
    //        IOrderDetrInfoRepository orderRepository)
    //    {
    //        _httpClientFactory = httpClientFactory;
    //        _logger = logger;
    //        _orderRepository = orderRepository;
    //    }

    //    // 添加 orderId 作为方法参数
    //    public async Task<string> ProcessPayment(string orderId, decimal amount)
    //    {
    //        try
    //        {
    //            var order = await _orderRepository.GetOrderDetailAsync(orderId);
    //            if (order.Amount != amount)
    //            {
    //                throw new ApplicationException($"金额不匹配: 请求金额 ${amount}, 订单金额 ${order.Amount}");
    //            }

    //            var response = await ProcessPayPalPaymentAsync(amount, order.Currency);

    //            await _orderRepository.UpdateOrderStatusAsync(orderId, "Completed");

    //            return $"PayPal支付成功! 订单: {orderId}, 交易ID: {response.TransactionId}";
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex, "PayPal支付处理失败");
    //            await TryUpdateOrderStatus(orderId, "Failed");
    //            throw new ApplicationException("PayPal支付处理失败", ex);
    //        }
    //    }

    //    private async Task TryUpdateOrderStatus(string orderId, string status)
    //    {
    //        try
    //        {
    //            await _orderRepository.UpdateOrderStatusAsync(orderId, status);
    //        }
    //        catch (Exception ex)
    //        {
    //            _logger.LogError(ex, "更新订单状态失败");
    //        }
    //    }

    //    private async Task<PayPalResponse> ProcessPayPalPaymentAsync(decimal amount, string currency)
    //    {
    //        using var client = _httpClientFactory.CreateClient("PayPal");
    //        var request = new PayPalRequest(amount, currency);

    //        var response = await client.PostAsJsonAsync("/v1/payments", request);
    //        response.EnsureSuccessStatusCode();

    //        return await response.Content.ReadFromJsonAsync<PayPalResponse>() ??
    //            throw new InvalidOperationException("无法解析PayPal响应");
    //    }

    //    private record PayPalRequest(decimal Amount, string Currency);
    //    private record PayPalResponse(string TransactionId);
    //}
    public class PayPalPayment : IPaymentService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<PayPalPayment> _logger;
        private readonly IOrderDetrInfoRepository _orderRepository;

        public PayPalPayment(
            IHttpClientFactory httpClientFactory,
            ILogger<PayPalPayment> logger,
            IOrderDetrInfoRepository orderRepository)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
            _orderRepository = orderRepository;
        }

        public async Task<string> ProcessPayment(string orderId, decimal amount)
        {
            OrderDetail order = null;
            try
            {
                // 确保在相同的作用域内完成所有数据库操作
                order = await _orderRepository.GetOrderDetailAsync(orderId);

                if (order.Amount != amount)
                {
                    throw new ApplicationException($"金额不匹配: 请求金额 ${amount}, 订单金额 ${order.Amount}");
                }

                var response = await ProcessPayPalPaymentAsync(amount, order.Currency);

                await _orderRepository.UpdateOrderStatusAsync(orderId, "Completed");

                return $"PayPal支付成功! 订单: {orderId}, 交易ID: {response.TransactionId}";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "PayPal支付处理失败");

                if (order != null)
                {
                    try
                    {
                        await _orderRepository.UpdateOrderStatusAsync(orderId, "Failed");
                    }
                    catch (Exception updateEx)
                    {
                        _logger.LogError(updateEx, "更新订单状态失败");
                    }
                }

                throw; // 将异常抛出给上层处理
            }
        }

        private async Task<PayPalResponse> ProcessPayPalPaymentAsync(decimal amount, string currency)
        {
            using var client = _httpClientFactory.CreateClient("PayPal");
            var request = new PayPalRequest(amount, currency);

            var response = await client.PostAsJsonAsync("/v1/payments", request);
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadFromJsonAsync<PayPalResponse>() ??
                throw new InvalidOperationException("无法解析PayPal响应");
        }

        private record PayPalRequest(decimal Amount, string Currency);
        private record PayPalResponse(string TransactionId);
    }
}
